<?php
include_once 'admin.php';
class adminFlashBuyController extends adminController {

    public function __construct() {
        parent::__construct();
    }
    /**
     * 闪购管理列表
     */
    public function dogetFlashList() {
        $code   = common::request('code','R','');//闪购编号
        $name   = common::request('name','R','');//名称
        $startTime = common::request('startTime','R','');//闪购开始时间
        $endTime = common::request('endTime','R','');//闪购结束时间
        $status = common::request('status','R',0);//状态
        $type = common::request('type','R',0);//状态
        $is_shihuo = common::request('is_shihuo','R',0);
        $listNum = 20;
        $p = common::request('p', 'G', 1);
        $start = ($p - 1) * $listNum;
        $parameter = '';
        $params = [];
        if (trim($code)) {
            $parameter .= '&code='."$code";
            $params['code'] = $code;
        }
        if (trim($name)) {
            $parameter .= '&title='."$name";
            $params['name'] = $name;
        }
        if ($status) {
            $parameter .= '&status='."$status";
            $params['status'] = $status;
        }
        if ($startTime) {
            $parameter .= '&startTime='."$startTime";
            $params['startTime'] = $startTime;
        }
        if ($endTime) {
            $parameter .= '&endTime='."$endTime";
            $params['endTime'] = $endTime;
        }
        if ($is_shihuo){
            $parameter .= '&is_shihuo=1';
            $params['is_shihuo'] = 1;
        }
        if($type){
            $parameter .= '&type='."$type";
            $params['type'] = $type;
        }

        $params['start'] = $start;
        $params['limit'] = $listNum;
        $info = $this->load('flashBuy')->getFlashBuyList($params);
        if($info) {
            $arrStatus = array(
                -5=>'已删除',
                0=>'未开始',
                5=>'进行中',
                10=>'已结束'
            );
            foreach ($info as $key=>$val) {
                $startTime2 = $val['start_time'] ? date('Y-m-d H:i:s',$val['start_time']) : '';
                $endTime2 = $val['end_time'] ? date('Y-m-d H:i:s',$val['end_time']) : '';
                $info[$key]['formatTime'] = $startTime2.'--'.$endTime2;
                $arrProTitle = $this->load('adminErp')->getProductInfoByObjectId($val['id'],'code,title',5);
                $info[$key]['goodsNameList'] = $arrProTitle && isset($arrProTitle[0]['title']) ? $arrProTitle[0]['title'] : '';
                $info[$key]['pcode'] = $arrProTitle && isset($arrProTitle[0]['title']) ? $arrProTitle[0]['code'] : '';
                $info[$key]['statusMsg'] = isset($arrStatus[$val['status']]) ? $arrStatus[$val['status']] : '未知状态';
                $info[$key]['images'] = json_decode($info[$key]['images']);
                $info[$key]['image'] = $info[$key]['image'];
                if(!empty( $info[$key]['images'])){
                    $info[$key]['image'] = current($info[$key]['images']);
                }
            }
        }
        $total = $this->load('flashBuy')->total;
        require FILE . 'lib/page.class.php';
        $page = new Page($total, $listNum, $parameter);
        $pageStr = $page->show();

        $this->view->assign('info', $info);
        $this->view->assign('pageStr', $pageStr);
        $this->view->assign('name', $name);
        $this->view->assign('code', $code);
        $this->view->assign('status', $status);
        $this->view->assign('type', $type);
        $this->view->assign('startTime', $startTime);
        $this->view->assign('endTime', $endTime);
        $this->view->display('flashBuy/flashBuyList');
    }

    /**
     * ajax 删除闪购
     */
    public function doajaxDelFlashBuy() {
        $flashId =  common::request('flashId','P',0);//闪购ID
        $result = $this->load('flashBuy')->saveFlashStatus(1,$flashId);
        if ($result) {
            echo json_encode(array('status'=>'ok','error_msg'=>'操作成功'));exit;
        }
        echo json_encode(array('status'=>'fail','error_msg'=>'操作失败'));exit;
    }

    /**
     *结束闪购
     */
    public function doajaxOverFlashBuy() {
        $flashId =  common::request('flashId','P',0);//闪购ID
        $result = $this->load('flashBuy')->saveFlashStatus(2,$flashId);
        if ($result) {
            echo json_encode(array('status'=>'ok','error_msg'=>'操作成功'));exit;
        }
        echo json_encode(array('status'=>'fail','error_msg'=>'操作失败'));exit;
    }

    /**
     * page 创建闪购
     */
    public function doaddFlashBuy() {
        $flashId =  common::request('flashId','R',0);//闪购ID
        $pcode = trim(common::request('pcode','R',''));//货品CODE
        $type = trim(common::request('type','R',''));
        $shihuoGrouponId = trim(common::request('shihuoGrouponId','R',''));//货品CODE
        $arrInfo = [];
        $productInfo = [];
        $list = [];
        $low_first_cost = INF;

        if(!empty($shihuoGrouponId)){
            $result = $this->db->getRow('select id from r_flash_sales where shihuo_grouponid='.$shihuoGrouponId);
            $flashId = $result['id'];
        }

        if ($flashId) {
            $arrInfo = $this->load('flashBuy')->getFlashBuyInfo($flashId);
            if (!$arrInfo) {
                common::tips('闪购不存在');exit;
            }

            $arrInfo['formatPreHotTime'] = $arrInfo['warmup_time'] ? date('Y-m-d H:i:s',$arrInfo['warmup_time']) : '';
            $arrInfo['formatStartTime'] = $arrInfo['start_time'] ? date('Y-m-d H:i:s',$arrInfo['start_time']) : '';
            $arrInfo['formatEndTime'] = $arrInfo['end_time'] ? date('Y-m-d H:i:s',$arrInfo['end_time']) : '';
            $arrInfo['images'] = json_decode($arrInfo['images']);

            $list = $this->load('goods')->getFlashGoodsList($flashId);  //查询闪购商品
            $arrInfo['gear_id'] = $arrInfo['gear_id']=='0'?'':$arrInfo['gear_id'];
        }else if(!empty($shihuoGrouponId)){
            $result = $this->db->getRow('select * from r_gear_shihuogroupon where groupon_id='.$shihuoGrouponId); 
            if(empty($result)){
                  echo '数据不存在';exit;
            }
            $arrInfo['shihuo_grouponid'] = $result['groupon_id'];
            $arrInfo['title'] = $result['title'];
            $arrInfo['warmup_time'] = $result['start_time'];
            $arrInfo['start_time'] = $result['start_time'];
            $arrInfo['end_time'] = $result['finish_time'];
            $arrInfo['cost_price'] = $result['original_price'];
            $arrInfo['low_price'] = $result['price'];
            $arrInfo['image_content'] = $result['memo'];
            $arrInfo['images'] = array($result['img_path']);
            $arrInfo['status'] = 5;
            $arrInfo['type'] = 2;

            $arrInfo['formatPreHotTime'] = $arrInfo['warmup_time'];
            $arrInfo['formatStartTime'] = $arrInfo['start_time'];
            $arrInfo['formatEndTime'] = $arrInfo['end_time'];
        }

    
        if (!$list && $pcode) {
            $productInfo = $this->load('adminErp')->getGoodsListByProductCode($pcode);
            if (!$productInfo) {
                common::tips('货品不存在!');exit;
            }
            foreach($productInfo['childGoods'] as $goods){
                if($goods['firstCost'] < $low_first_cost){
                    $low_first_cost = $goods['firstCost'];
                }
            }
        }
        if(!isset($arrInfo['type'])){
            $arrInfo['type'] = $type;
        }

        $this->view->assign('flashInfo', $arrInfo);
        $this->view->assign('flashId', $flashId);
        $this->view->assign('low_first_cost',$low_first_cost);
        $this->view->assign('flashSaleStatus',common::$flashSaleStatus);
        
        $this->view->assign('productInfo', $productInfo);
        $this->view->assign('pcode', $pcode);
        $this->view->assign('list', $list);
        $this->view->display('flashBuy/addFlashBuy');
    }

    /**
     * 上传闪购图片
     */
    public function doajaxUploadImage() {
        if (!$_FILES || ($_FILES['imgFile']['size'] == 0)) {
            echo json_encode(array('status'=>'fail','error_msg'=>'请选择上传文件!'));
            exit;
        }
        $imageName ='admin_flashBuy_'.md5(microtime(TRUE).$_FILES['imgFile']['name']);
        $image_url = $this->load('qiniu')->uploadQiNiuImg('imgFile',$imageName);
        if (!$image_url) {
            echo json_encode(array('status'=>'fail','error_msg'=>'上传失败'));exit;
        }
        echo json_encode(array('status'=>'ok','error_msg'=>'上传成功','image'=>$image_url));
    }

    /**
     * ajax 创建闪购
     */
    public function doajaxAddFlashBuy() {
        $id = common::request('flashId','R',0);//闪购ID
        $name = common::request('name','R','');//闪购名称
        $image  = common::request('image','R','');//闪购图片
        $startTime = common::request('startTime','R',0);//开始时间
        $endTime = common::request('endTime','R',0);//结束时间
        $preHotTime = common::request('preHotTime','R',0);//预热时间
        $costPrice = common::request('costPrice','R',0);//原价
        $introduce = common::request('introduce','R','');//图文说明
        $introduce2 = common::request('introduce2','R','');//参数规格说明
        $weidian_link = common::request('weidian_link','R','');//微店链接
        $low_price = common::request('low_price','R',0);
        $gear_id = common::request('gear_id','R',0);
        $type = common::request('type','R',0);
        $status =  common::request('status','R',0);
        $shihuo_grouponid = common::request('shihuo_grouponid','R',0);

        if ($id) {
           $arrInfo = $this->load('flashBuy')->getFlashBuyInfo($id,'id,status');
            if (!$arrInfo) {
                echo json_encode(array('status'=>'fail','error_msg'=>'闪购不存在'));exit;
            }
            //if ($arrInfo['status'] <> 0) {
            //    echo json_encode(array('status'=>'fail','error_msg'=>'闪购只在未开始状态下可编辑'));exit;
            //}
        }
        if($type==2&&empty($shihuo_grouponid)){
            echo json_encode(array('status'=>'fail','error_msg'=>'识货ID必填'));exit;
        }

        if (!trim($name)) {
            echo json_encode(array('status'=>'fail','error_msg'=>'闪购标题必填'));exit;
        }
        if (!$image || !isset($image[0]) || !$image[0]) {
            echo json_encode(array('status'=>'fail','error_msg'=>'图片必传'));exit;
        }
        if (!trim($startTime)) {
            echo json_encode(array('status'=>'fail','error_msg'=>'闪购开始时间必填'));exit;
        }
        //if (!trim($endTime)) {
        //    echo json_encode(array('status'=>'fail','error_msg'=>'闪购结束时间必填'));exit;
        //}

        if($shihuo_grouponid){
            $type = 2;
        }else if(empty($endTime)){
            $type = 3;
        }else{
            $type= 1;
        }

        if (!preg_match('/^[1-9][0-9]*(\.[0-9]{1,2})?$/', $costPrice,$match)
            && !preg_match('/^[0-9]\.0[1-9]$/', $costPrice,$match2)
            && !preg_match('/^[0-9]\.[1-9][0-9]?$/', $costPrice,$match3)) {
            echo json_encode(array('status'=>'fail','error_msg'=>'原价必须>0,最多2位小数')); exit;
        }

        if (!trim($introduce)) {
            echo json_encode(array('status'=>'fail','error_msg'=>'图文内容必填'));exit;
        }
        $fields = array();
        $fields['id'] = $id;
        $fields['title'] = $name;
        $fields['image'] = $image[0];
        $fields['images'] = json_encode($image);
        $fields['warmupTime'] = $preHotTime;
        $fields['startTime'] = $startTime;
        $fields['endTime'] = $endTime;
        $fields['costPrice'] = $costPrice;
        $fields['imageContent'] = $introduce;
        $fields['optionContent'] = $introduce2;
        $fields['weidian_link'] = $weidian_link;
        $fields['low_price'] = $low_price;
        $fields['shihuo_grouponid'] = $shihuo_grouponid;
        $fields['gear_id'] = $gear_id;
        $fields['type'] = $type;
        $fields['status'] = $status;
        $result = $this->load('flashBuy')->addFlashBuy($fields);
        if ($result) {
            echo json_encode(array('status'=>'ok','error_msg'=>'操作成功','url'=>'index.php?c=adminFlashBuy&a=getFlashList','id'=>empty($id) ? $result : $id));exit;
        }
        echo json_encode(array('status'=>'fail','error_msg'=>'操作失败'));


    }

    /**
     * 闪购商品配置
     */
    public function doaddFlashGoods() {
        $flashId = common::request('flashId','R',0);//闪购ID
        if (!$flashId) {
            common::tips('参数丢失!');exit;
        }
        $arrInfo = $this->load('flashBuy')->getFlashBuyInfo($flashId);
        if (!$arrInfo) {
            common::tips('闪购不存在');exit;
        }
        $pcode = trim(common::request('pcode','R',''));//货品CODE
        $productInfo = [];
        $list = $this->load('goods')->getFlashGoodsList($flashId);  //查询闪购商品
        if (!$list) {
            if ($pcode) {
                $productInfo = $this->load('adminErp')->getGoodsListByProductCode($pcode);
                if (!$productInfo) {
                    common::tips('货品不存在!');exit;
                }
            }
        }

        $this->view->assign('productInfo', $productInfo);
        $this->view->assign('flashId', $flashId);
        $this->view->assign('pcode', $pcode);
        $this->view->assign('list', $list);
        $this->view->assign('flashInfo', $arrInfo);
        $this->view->display('flashBuy/addFlashGoods');
    }

    /**
     * ajax 闪购商品配置
     */
    public function doajaxaddFlashGoods() {
        $flashId = common::request('flashId','R',0);//闪购ID
        $pcode = trim(common::request('pcode_2','R',''));//货品CODE
        $gid = common::request('gid','R',0);//货品ID
        $stockIntoCnt = common::request('stockIntoCnt','R',0);//入库数量
        $price = common::request('price','R',0);//单价
        if (!$flashId || !$gid || !$stockIntoCnt || !$price) {
            echo json_encode(array('status'=>'fail','error_msg'=>'参数丢失')); exit;
        }
        $arrInfo = $this->load('flashBuy')->getFlashBuyInfo($flashId);
        if (!$arrInfo) {
            echo json_encode(array('status'=>'fail','error_msg'=>'闪购不存在')); exit;
        }
        //查询是否有闪购货品（1个闪购只能有一个货品）
        $boolIsExistFlashGoods = $this->load('adminErp')->getIsExistGoodsByObjectId($flashId,adminErpModel::FLASHSHOP);
        if ($boolIsExistFlashGoods) {
            echo json_encode(array('status'=>'fail','error_msg'=>'闪购商品配置已存在,只支持一个商品')); exit;
        }
        $productInfo = $this->load('adminErp')->getGoodsListByProductCode($pcode);//货品信息 做校验
        if (!$productInfo) {
            echo json_encode(array('status'=>'fail','error_msg'=>'货品不存在')); exit;
        }
        if ($productInfo['status'] == 0) {
            echo json_encode(array('status'=>'fail','error_msg'=>'货品不可售')); exit;
        }
        if (!isset($productInfo['childGoods']) || !$productInfo['childGoods']) {
            echo json_encode(array('status'=>'fail','error_msg'=>'货品的规格商品不存在，请去库存增加')); exit;
        }

        $bindFlashId = $this->in_db('erpManageDb')->getOne("select object_id from r_object_goods where type=5 and status=0 and product_id={$productInfo['id']}");
        if (!empty($bindFlashId)) {
            echo json_encode(array('status'=>'fail','error_msg'=>'货品已经绑定其它闪购 ' . $bindFlashId)); exit;
        }
        $arrChildGoods = [];
        foreach ($productInfo['childGoods'] as $key=>$val) {
            $arrChildGoods[$val['gid']] = $val['realStockNum'];
        }
        /*检测数据start*/
        $fields = [];
        foreach($gid as $key=>$val) {
            if (!(int)$val) {
                echo json_encode(array('status'=>'fail','error_msg'=>'第'.($key+1).'行规格参数丢失')); exit;
            }
            if (!array_key_exists($val,$arrChildGoods)) {
                echo json_encode(array('status'=>'fail','error_msg'=>'第'.($key+1).'行规格参数有误')); exit;
            }
            if (!preg_match('/^[0-9]+$/',$stockIntoCnt[$key],$match)) {
                echo json_encode(array('status'=>'fail','error_msg'=>'第'.($key+1).'行入库数量是正整数且必须>=0')); exit;
            }
            if ($stockIntoCnt[$key] >0
                && !preg_match('/^[1-9][0-9]*(\.[0-9]{1,2})?$/', $price[$key],$match)
                && !preg_match('/^[0-9]\.0[1-9]$/', $price[$key],$match2)
                && !preg_match('/^[0-9]\.[1-9][0-9]?$/', $price[$key],$match3)) {
                echo json_encode(array('status'=>'fail','error_msg'=>'第'.($key+1).'行单价必须>0,最多2位小数')); exit;
            }
            //计划数量小于等于实际库存
            if ($stockIntoCnt[$key] >0 && ($stockIntoCnt[$key] > $arrChildGoods[$val])) {
                echo json_encode(array('status'=>'fail','error_msg'=>'第'.($key+1).'行计划数量不能大于实际库存')); exit;
            }
            $fields[] = array('gid'=>(int)$val,'stockIntoCnt'=>(int)$stockIntoCnt[$key],'price'=>(float)round($price[$key],2));
        }
        /*检测数据end*/
        $okCnt =0;
        $num = 0;
        foreach ($fields as $key=>$val) {
            $r = $this->load('goods')->addFlashGoods($flashId,$productInfo['id'],$val['gid'],$val['stockIntoCnt'],$val['price']);
            if ($r){
                $okCnt++;
                $num += $val['stockIntoCnt'];
            }
        }


        if ($okCnt > 0) {
            //更新闪购总库存
            $this->load('flashBuy')->setFlashCostPrice($flashId,$num);
            echo json_encode(array('status'=>'ok','error_msg'=>'成功生成'.$okCnt.'条记录,失败'.(count($fields)-$okCnt).'条','url'=>'?c=adminFlashBuy&a=addFlashGoods&flashId='.$flashId)); exit;
        }
        echo json_encode(array('status'=>'fail','error_msg'=>'成功生成'.$okCnt.'条记录,失败'.(count($fields)-$okCnt).'条')); exit;


    }

    /**
     * ajax 删除闪购商品
     */
    public function doajaxDelFlashGoods() {
        $flashId = common::request('flashId','R',0);//闪购ID
        $arrInfo = $this->load('flashBuy')->getFlashBuyInfo($flashId,'id,status');
        if (!$arrInfo) {
            echo json_encode(array('status'=>'fail','error_msg'=>'闪购不存在'));exit;
        }
        if ($arrInfo['status'] <> 0) {
            echo json_encode(array('status'=>'fail','error_msg'=>'闪购只在未开始状态下可编辑'));exit;
        }
        $r = $this->load('goods')->saveFlashStatus($flashId);
        if ($r) {
            //更新闪购总库存
            $this->load('flashBuy')->setFlashCostPrice($flashId,0);
            echo json_encode(array('status'=>'ok','error_msg'=>'操作成功','url'=>'index.php?c=adminFlashBuy&a=getFlashList'));exit;
        }
        echo json_encode(array('status'=>'fail','error_msg'=>'操作失败'));


    }
    
    /*
     * 设为今日主打
     */
    public function dosetFeatured(){
        $flashId = common::request('flashId','R',0);//闪购ID
        $is_featured = common::request('is_featured','R',0);
        if(!$flashId){
            die('id 错误，<a href="/index.php?c=adminFlashBuy&a=getFlashList">点击返回</a>');
        }
        $this->load('flashBuy')->setFeature($flashId,$is_featured);
        die('编辑完成，<a href="/index.php?c=adminFlashBuy&a=getFlashList">点击返回</a>');
    }
}